<template>
  <div class="upload-container">
    <el-button :style="{background:color,borderColor:color}"
               icon="el-icon-upload"
               size="mini"
               type="primary"
               @click="upload">上传</el-button>
    <el-dialog :visible.sync="dialogVisible"
               :modal="false"
               :show-close="false">
      <div class="imgList">
        <div v-for="(item,i) in fileList"
             :key="i"
             class="listItem">
          <img :src="item.url"
               alt
               class="imgpng">
          <div class="deleteBtn"
               @click="deleteitem(item)">
            <i class="el-icon-delete" />
          </div>
        </div>
      </div>
      <div class="wrapimg">
        <el-button class="uploadbtn"
                   size="small"
                   type="primary"
                   plain
                   @click="onPickFile">图片上传</el-button>
        <input v-show="false"
               ref="fileInput"
               type="file"
               accept="image/*"
               @change="tirggerFile($event)">
      </div>
      <span slot="footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary"
                   @click="handleSubmit">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'EditorSlideUpload',
  props: {
    color: {
      // 上传按钮背景色
      type: String,
      default: '#1890ff'
    }
  },
  data () {
    return {
      dialogVisible: false, // 上传图片弹窗是否可见
      fileList: [], // 上传的文件列表
      imageUrl: '' // 选中图片的base64 字符串
    }
  },
  created () { },
  methods: {
    // 点击上传按钮
    upload () {
      // 初始化数据
      this.fileList = []
      this.dialogVisible = true
    },
    // 点击取消按钮
    cancel () {
      this.dialogVisible = false
      // 初始化数据
      this.fileList = []
    },
    // 点击确定
    handleSubmit () {
      this.$emit('successCBK', this.fileList)
      this.listObj = {}
      this.fileList = []
      this.dialogVisible = false
    },

    // 点击按钮触发隐藏的input
    onPickFile () {
      this.$refs.fileInput.value = null
      this.$refs.fileInput.click()
    },
    // 选择获取文件
    tirggerFile ($event) {
      // 限制图片大小 为5M
      if ($event.target.files[0].size > 2 * 1024 * 1024) {
        this.$message.error('不能上传大于2M的图片')
        return false
      }
      const self = this
      const file = $event.target.files[0]
      // 截取字段
      const type = file.type.split('/')[1]
      const fileName = file.name
      if (fileName.lastIndexOf('.') <= 0) {
        this.$message.error('请选择图片类型文件')
        return false
      }
      const fileReader = new FileReader() // 内置方法new FileReader()   读取文件

      fileReader.addEventListener('load', async () => {
        // var flag = true
        // var flag = await this.limitWH(fileReader.result)
        // if (flag) {
          this.imageUrl = fileReader.result
          // base64转bolb
          const bolb = self.dataURLtoBlob(fileReader.result)
          const formData = new FormData()
          // ,mazey-test.webm
          formData.append('file', bolb, `mazey-test.${type}`)
          formData.append('file_type', 1)
          formData.append('per_page', 8)
          // 拿到数据发送给服务器
          this.common.getUpload(formData).then(res => {
            this.fileList.push({ url: this.common.img_url + res.data.data })
            this.$forceUpdate()
          })
        // }
      })
      fileReader.readAsDataURL(file)
    },
    // 限制图片宽高
    limitWH (url) {
      var that = this
      // 创建对象
      var img = new Image()
      img.src = url
      return new Promise(resolve => {
        // 加载完成执行
        img.onload = function () {
          if (img.width !== 750) {
            that.$message.error('请选择宽度为750的图片')
            return resolve(false)
          } else {
            return resolve(true)
          }
        }
      })
    },
    // base64转blob
    dataURLtoBlob (dataurl) {
      var arr = dataurl.split(',')
      var mime = arr[0].match(/:(.*?);/)[1]
      var bstr = atob(arr[1])
      var n = bstr.length
      var u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new Blob([u8arr], { type: mime })
    },
    // 删除图片
    deleteitem (item) {
      for (let i = 0; i < this.fileList.length; i++) {
        if (this.fileList[i].url == item.url) {
          this.fileList.splice(i, 1)
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.wrapimg {
  width: 100%;
  background-color: #fbfdff;
  border: 1px dashed #c0ccda;
  border-radius: 6px;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  height: 148px;
  line-height: 146px;
  vertical-align: top;
  text-align: center;
}
.uploadbtn {
  display: inline-block;
  text-align: center;
  cursor: pointer;
  outline: 0;
}
// 图片列表
.imgList {
  margin: 0;
  vertical-align: top;
  .listItem {
    overflow: hidden;
    background-color: #fff;
    border: 1px solid #c0ccda;
    border-radius: 6px;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    width: 148px;
    height: 148px;
    margin: 0 8px 8px 0;
    display: inline-block;
    position: relative;
    .imgpng {
      width: 100%;
      height: 100%;
      border-style: none;
    }
  }
}
.deleteBtn {
  position: absolute;
  top: 0;
  right: 0;
  font-size: 16px;
  width: 20px;
  height: 20px;
  text-align: center;
  cursor: pointer;
  background: rgba(0, 0, 0, 0.5);
  color: #fff;
  border-radius: 2px;
}
</style>
